<template>
  <view :data-theme="globPrimary">
    <u-navbar
      :immersive="true"
      z-index="999"
      :border-bottom="false"
      :background="{ background: globPrimaryColor }"
      back-icon-color="#ffffff"
      title-color="#ffffff"
      :custom-back="onBack"
    >
      <view class="head_view">
        <view class="title" @click="navbarClick">我的推广</view>
        <u-icon name="xiala-" v-if="!show" custom-prefix="edu-icon" size="30" color="#fff"></u-icon>
        <u-icon name="shangla" v-else custom-prefix="edu-icon" size="30" color="#fff"></u-icon>
      </view>
      <view slot="right" class="navbar-right" @click="$u.route('/pageUser/user/incomeDetails')"
        >明细</view
      >
    </u-navbar>
    <view class="income-top" :style="{ background: globPrimaryColor }">
      <view
        :style="{
          width: '100%',
          height: globNavbarHeight + globStatusBarHeight + 'px',
        }"
      ></view>
      <view class="u-flex u-row-center u-flex-1">
        <view class="price">
          {{ setting.appMoneySymbol }}
          <text>{{ income || 0 }}</text>
        </view>
      </view>
    </view>

    <mescroll-body
      :top="mescrollTop"
      :bottom="mescrollBottom"
      :up="upOption"
      :down="downOption"
      ref="mescrollRef"
      @init="mescrollInit"
    >
      <view class="income-wrapper">
        <view class="income-recharge">
          <view class="title">提现</view>
          <view class="list">
            <text>{{ setting.appMoneySymbol }}</text>
            <u-input v-model="value" type="number" :clearable="false" placeholder="输入提现金额" />
          </view>
          <view class="proportion"
            >注：提现到余额后不能再转至银行卡或支付宝，转账比例为{{ proportion }}</view
          >
        </view>
        <view class="income-group">
          <u-radio-group v-model="paywayRadio" :active-color="globPrimaryColor" size="44" wrap>
            <u-radio v-for="(item, index) in payway" :name="item" :key="index">
              <view class="u-flex" v-if="item == 'lcnpay'">
                <u-image
                  width="44rpx"
                  height="44rpx"
                  :src="require('@/static/images/order_yue_icon.png')"
                ></u-image>
                <view class="text">余额({{ balance }})</view>
              </view>
              <view class="u-flex" v-else-if="item == 'alipay'">
                <u-image
                  width="44rpx"
                  height="44rpx"
                  :src="require('@/static/images/order_zhifubao_icon.png')"
                ></u-image>
                <view class="text">支付宝</view>
              </view>
              <view class="u-flex" v-else-if="item == 'wxpay'">
                <u-image
                  width="44rpx"
                  height="44rpx"
                  :src="require('@/static/images/order_wechat_icon.png')"
                ></u-image>
                <view class="text">微信</view>
              </view>
            </u-radio>
          </u-radio-group>
        </view>
        <view class="income-checkbox">
          <u-checkbox v-model="checked" size="30" :active-color="globPrimaryColor"
            >我已阅读并同意
          </u-checkbox>
          <text
            @click="
              $u.route('/pages/protocol', {
                key: 'payment',
              })
            "
          >
            《{{ getAgreementTitle('payment') }}》
          </text>
        </view>
      </view>
    </mescroll-body>

    <view class="income-bottom">
      <view class="left">
        实付
        <text>{{ rechargePrice | formatCurrency }}</text>
      </view>
      <edu-button
        class="btn"
        type="primary"
        :disabled="btnDisabled"
        size="medium"
        shape="circle"
        @click="payBtn"
        >提现
      </edu-button>
    </view>
    <!-- 支付宝提交弹窗 -->
    <u-popup v-model="showAlipayPopup" mode="center" width="540" border-radius="14">
      <view class="alipay-wrapper">
        <view class="title">账户确认</view>
        <view class="account">是否提现到默认账号：</view>
        <view class="phone">{{ userInfo.phone | formatMask }}</view>
        <view class="input">
          <u-input v-model="alipayUserName" type="text" :clearable="false" placeholder="输入姓名" />
        </view>
        <edu-button
          class="btn"
          type="primary"
          :disabled="alipayBtnDisabled"
          size="medium"
          @click="handleAlipay"
          >立即提现
        </edu-button>
        <view
          class="link"
          @click="
            $u.route('/pageUser/user/incomeAlipayCash', {
              money: rechargePrice,
            })
          "
        >
          提现至其他账户
          <u-icon name="arrow-right"></u-icon>
        </view>
      </view>
    </u-popup>

    <!-- 头部弹窗 -->
    <u-popup mode="top" v-model="show" z-index="990">
      <view
        :style="{
          width: '100%',
          height: globNavbarHeight + globStatusBarHeight + 'px',
        }"
      ></view>
      <view class="popup_item">
        <view class="popup_content">
          <view
            class="list_popup"
            v-for="(i, index) in list"
            :key="index"
            @click="chose_click(index)"
          >
            <view v-if="list_id == index">{{ i }}</view>
            <view v-else>{{ i }}</view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import setting from '@/settings/projectSetting.js'
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
import { mapGetters, mapState } from 'vuex'
export default {
  mixins: [MescrollMixin],
  data() {
    return {
      setting,
      downOption: { use: false },
      upOption: { use: false },
      wechatLogin: '',
      show: false,
      title: '推广收入',
      list: ['推广收入', '推广课程', '推广用户'],
      list_id: 0,
      value: '',
      balance: '',
      income: '',
      payway: [], // 支付方式
      paywayRadio: '',
      proportion: '',
      checked: false,
      showAlipayPopup: false,
      alipayUserName: '',
    }
  },
  // 监听页面返回
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    this.onBack()
    return true
  },
  onShow() {
    this.getIncomeInfo()
    this.showAlipayPopup = false
  },
  onLoad() {
    // #ifdef H5
    let loc_href = encodeURIComponent(this.setting.appBaseUrl + '/pageUser/setting/wechatLogin')
    this.$edu.api
      .getConfigThirdlogin({
        redirect_uri: loc_href,
      })
      .then((res) => {
        this.wechatLogin = res.data.weixin
      })
    // #endif
  },
  computed: {
    ...mapState({
      getGlobOpenid: (state) => state.projectSetting.globOpenid,
    }),
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      globNavbarHeight: 'projectSetting/globNavbarHeight',
      globStatusBarHeight: 'projectSetting/globStatusBarHeight',
      userInfo: 'user/getUserInfo',
      getAgreementTitle: 'projectSetting/getAgreementTitle',
    }),
    rechargePrice() {
      if (this.value == '') {
        return 0
      } else {
        let pop = this.proportion.split(':')
        let num = ((this.value / pop[1]) * pop[0]).toFixed(2)
        return num
      }
    },
    alipayBtnDisabled() {
      return this.alipayUserName == '' ? true : false
    },
    btnDisabled() {
      return this.value > 0 && this.checked == true ? false : true
    },
    mescrollTop() {
      return uni.upx2px(350) + 10 + 'px'
    },
    mescrollBottom() {
      return uni.upx2px(98) + 'px'
    },
  },
  methods: {
    chose_click(_index) {
      if (_index == 0) {
        this.show = !this.show
      } else if (_index == 1) {
        this.$u.route('/pageUser/user/incomeCourse', {
          type: false,
        })
        this.show = !this.show
      } else if (_index == 2) {
        this.$u.route('/pageUser/user/incomeCourse', {
          type: true,
        })
        this.show = !this.show
      }
    },
    getIncomeInfo() {
      this.$edu.api.getUserIncome().then((res) => {
        const { data } = res
        this.balance = data.balance
        this.income = data.income
        this.proportion = data.ratio
        if (!this.$u.test.empty(data.encashment_way)) {
          const list = ['wxpay', 'alipay', 'lcnpay']
          const set1 = new Set(data.encashment_way)
          const set2 = new Set(list)
          let str = [...set1].filter((x) => set2.has(x))
          str.sort((prev, next) => {
            return list.indexOf(prev) - list.indexOf(next)
          })
          // #ifdef MP-WEIXIN
          // 小程序隐藏支付宝
          str.splice(
            str.findIndex((item) => item == 'alipay'),
            1
          )
          // #endif
          /* #ifdef H5 */
          var ua = window.navigator.userAgent.toLowerCase()
          if (ua.match(/micromessenger/i) == 'micromessenger') {
            str.splice(
              str.findIndex((item) => item == 'alipay'),
              1
            )
          }
          /* #endif */
          this.payway = str
          const val = list.find((k) => str.includes(k))
          this.paywayRadio = val
        }
      })
    },
    payBtn() {
      const _this = this
      if (this.paywayRadio === '') return
      const calc = {
        // 余额
        lcnpay: function () {
          _this.$edu.api
            .postUserIncomeEncashmentBalance({
              money: _this.rechargePrice,
            })
            .then((res) => {
              _this.getIncomeInfo()
              _this.$u.toast(res.msg)
              _this.value = ''
            })
            .catch((res) => {
              _this.$u.toast(res.msg)
            })
        },
        alipay: function () {
          _this.showAlipayPopup = true
        },
        wxpay: function () {
          // #ifdef H5
          _this.$edu.api
            .postUserIncomeEncashmentWxpay({
              money: _this.rechargePrice,
              redirect_uri: _this.setting.appBaseUrl + '/pageUser/user/weixinh5',
            })
            .then((res) => {
              window.location.href = res.data
            })
          // #endif
          // #ifdef MP-WEIXIN
          if (_this.getGlobOpenid) {
            _this.$edu.api
              .postUserIncomeEncashmentWxpay({
                wxpay_openid: _this.getGlobOpenid,
                money: _this.rechargePrice,
              })
              .then((res) => {
                _this.$u.toast(res.msg)
                setTimeout(() => {
                  _this.$edu.api.getUserIncome().then((res) => {
                    const { data } = res
                    _this.balance = data.balance
                    _this.income = data.income
                    _this.value = ''
                  })
                }, 1500)
              })
          } else {
            _this.$store.dispatch('projectSetting/setGlobWeixinAppid')
          }
          // #endif
          // #ifdef APP-PLUS
          uni.showLoading({
            title: '加载中',
          })
          uni.login({
            provider: 'weixin',
            success: (loginRes) => {
              let oauth = loginRes.authResult.openid
              _this.$edu.api
                .postUserIncomeEncashmentWxpay({
                  wxpay_openid: oauth,
                  money: _this.rechargePrice,
                })
                .then((res) => {
                  _this.$u.toast(res.msg)
                  setTimeout(() => {
                    uni.hideLoading()
                    _this.$edu.api.getUserIncome().then((res) => {
                      const { data } = res
                      _this.balance = data.balance
                      _this.income = data.income
                      _this.value = ''
                    })
                  }, 1500)
                })
            },
            fail: () => {
              uni.hideLoading()
            },
          })
          // #endif
        },
        run: function (fn) {
          return fn && fn()
        },
      }
      calc.run(calc[_this.paywayRadio])
    },
    // 支付宝提现
    handleAlipay() {
      this.showAlipayPopup = false
      this.$edu.api
        .postUserIncomeEncashmentAlipay({
          money: this.rechargePrice,
          alipay_user_name: this.alipayUserName,
          alipay_account: this.userInfo.phone,
        })
        .then((res) => {
          this.getIncomeInfo()
          this.$u.toast(res.msg)
          this.alipayUserName = ''
          this.value = ''
        })
    },
    navbarClick() {
      this.show = !this.show
    },
    // 返回上一页
    onBack() {
      this.$u.route({ type: 'switchTab', url: 'pages/user/index' })
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/.u-dropdown__menu {
  display: none !important;
  height: 0 !important;
}

/deep/.u-dropdown__content {
  top: 0 !important;
  height: calc(100vh - 44px) !important;
}

.head_view {
  text-align: center;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .title {
    color: white;
    margin-right: 10rpx;
    font-size: 36rpx;
    font-weight: bold;
  }
}

.navbar-right {
  color: #ffffff;
  font-size: 30rpx;
  margin-right: 30rpx;
}

.income-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 350rpx;
  z-index: 9;
  @include bg-color();
  display: flex;
  flex-direction: column;
  .price {
    color: #ffff;
    font-size: 40rpx;
    font-weight: 500;

    text {
      font-size: 64rpx;
    }
  }
}

.income-wrapper {
  .income-recharge {
    padding: 50rpx 30rpx;
    background-color: #ffffff;

    .title {
      font-size: 30rpx;
      font-weight: 400;
      color: $edu-main-color;
    }

    .list {
      display: flex;
      align-items: center;
      margin-top: 10rpx;
      border-bottom: 1px solid #f7f7f7;

      text {
        font-size: 36rpx;
        font-weight: 400;
        color: $edu-main-color;
        margin-right: 24rpx;
      }
    }

    .proportion {
      margin-top: 24rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: #b7bac1;
    }
  }

  .income-group {
    background-color: #ffffff;
    margin-top: 20rpx;
    padding: 0 30rpx;
    ::v-deep.u-radio-group {
      width: 100%;
    }

    .text {
      margin-left: 24rpx;
      font-size: 30rpx;
      font-weight: 400;
      color: $edu-content-color;
    }
    ::v-deep.u-radio {
      padding: 30rpx 0;
      display: flex;
      flex-direction: row-reverse;
      justify-content: space-between;
    }
  }

  .income-checkbox {
    margin-top: 20rpx;
    padding: 0 30rpx;
    display: flex;
    align-items: center;
    height: 120rpx;
    background-color: #fff;

    /deep/.u-checkbox__label {
      font-size: 28rpx;
      margin-right: 0;
    }

    text {
      @include text-color();
      font-size: 28rpx;
    }
  }
}

.income-bottom {
  width: 100%;
  height: 98rpx;
  background: #ffffff;
  box-shadow: 0 2rpx 14rpx 0 rgba(0, 0, 0, 0.06);
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  position: fixed;
  bottom: 0;
  z-index: 9;

  /* #ifdef MP-WEIXIN || APP-PLUS */
  justify-content: space-between;
  /* #endif */

  .left {
    font-size: 26rpx;
    font-weight: 400;
    color: $edu-main-color;
    display: flex;
    align-items: center;

    text {
      margin-left: 10rpx;
      font-size: 32rpx;
      font-weight: 500;
      color: $edu-price-color;
    }
  }

  .btn {
    margin-right: 0;
  }
}

.alipay-wrapper {
  padding: 40rpx;
  text-align: center;

  .title {
    font-size: 36rpx;
    font-weight: 400;
    color: $edu-main-color;
  }

  .account {
    margin-top: 18rpx;
    font-size: 30rpx;
    font-weight: 400;
    color: $edu-content-color;
  }

  .phone {
    margin-top: 10rpx;
    font-size: 30rpx;
    font-weight: 400;
    color: $edu-main-color;
  }

  .input {
    padding: 0 24rpx;
    margin-top: 16rpx;
    height: 72rpx;
    border-radius: 8rpx;
    border: 1px solid #dddddd;
    /* #ifdef MP-WEIXIN */
    margin-bottom: 20rpx;
    /* #endif */
  }

  .btn {
    margin-top: 30rpx;
    width: 100%;
  }

  .link {
    margin-top: 24rpx;
    font-size: 30rpx;
    font-weight: 400;
    color: $edu-tips-color;
  }
}

.radio_item {
  height: auto;
  width: 100%;
  overflow: hidden;

  .radio_li {
    margin-top: 60rpx;
    display: flex;
    justify-content: space-between;

    .left_item {
      width: 60%;
      display: flex;
      height: 44rpx;

      .text {
        @include text-color();
        margin-left: 24rpx;
      }
    }
  }
}

.popup_item {
  height: auto;
  width: 100%;

  .popup_head {
    display: flex;
    justify-content: space-between;
    align-items: center;

    @include bg-color();
    .popop_cen {
      color: #303133;
      display: flex;

      .font {
        font-size: 36rpx;
        font-weight: bold;
        margin-right: 12rpx;
        color: #ffffff;
      }
    }

    .popop_r {
      color: #ffffff;
      font-size: 30rpx;
    }
  }

  .popup_content {
    padding-left: 30rpx;
    padding-right: 30rpx;

    .list_popup {
      height: 89rpx;
      line-height: 87rpx;
      font-size: 28rpx;
    }
  }
}

.popup_content .list_popup:not(:last-child) {
  border-bottom: 1px solid #f7f7f7;
}

.txt_color {
  @include text-color();
}
</style>
